import request from '@/utils/request'
import axios from 'axios'

// 查询基础镜像列表
export function listBaseImages(query) {
  return request({
    url: '/harbor/base-images',
    method: 'get',
    params: query
  })
}

// 查询基础镜像详细
export function getBaseImage(imageId) {
  return request({
    url: '/packages/image/base/' + imageId,
    method: 'get'
  })
}

// 新增基础镜像
export function addBaseImage(data) {
  return request({
    url: '/packages/image/base',
    method: 'post',
    data: data
  })
}

// 修改基础镜像
export function updateBaseImage(data) {
  return request({
    url: '/packages/image/base',
    method: 'put',
    data: data
  })
}

// 删除基础镜像
export function delBaseImage(imageId) {
  return request({
    url: '/packages/image/base/' + imageId,
    method: 'delete'
  })
}

// 查询服务镜像列表
export function listServiceImages(query) {
  return request({
    url: '/harbor/all-images',
    method: 'get',
    params: query
  })
}

// 查询服务镜像详细
export function getServiceImage(imageId) {
  return request({
    url: '/packages/image/service/' + imageId,
    method: 'get'
  })
}

// 新增服务镜像
export function addServiceImage(data) {
  return request({
    url: '/packages/image/service',
    method: 'post',
    data: data
  })
}

// 修改服务镜像
export function updateServiceImage(data) {
  return request({
    url: '/packages/image/service',
    method: 'put',
    data: data
  })
}

// 删除服务镜像
export function delServiceImage(imageId) {
  return request({
    url: '/packages/image/service/' + imageId,
    method: 'delete'
  })
}

// 上传服务镜像文件
export function uploadServiceImageFile(formData) {
  // 创建独立的axios实例用于文件上传，避免请求拦截器覆盖Content-Type
  const uploadAxios = axios.create({
    baseURL: process.env.VUE_APP_BASEURL,
    timeout: 120000 // 增加超时时间到120秒，文件上传可能需要更长时间
  });
  
  // 添加token到headers
  let user = JSON.parse(localStorage.getItem("honey-user") || '{}')
  const headers = {
    'Content-Type': 'multipart/form-data'
  };
  
  if (user.token) {
    headers['Authorization'] = 'Bearer ' + user.token;
    headers['token'] = user.token;
  }
  
  // 添加上传进度监听
  const config = {
    headers,
    timeout: 120000,
    onUploadProgress: (progressEvent) => {
      const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
      console.log(`上传进度: ${percentCompleted}%`);
    }
  };
  
  return uploadAxios.post('tenant/load-image', formData, config)
}
